import type { Parameter, PlanDocument } from '@/app/api/plans/route';
import { useDownload } from '@/hooks/useDownload';
import { clientFetch } from '@/utils/request';
import {
  Button,
  Collapsible,
  Popconfirm,
  Toast,
  Tooltip,
} from '@douyinfe/semi-ui';
import { Icon } from '@iconify/react';
import clsx from 'clsx';
import { format } from 'date-fns';
import { useState } from 'react';

interface Props {
  className?: string;
  record: PlanDocument;
}

export default function PlanCard({ className, record }: Props) {
  const [isOpen, setIsOpen] = useState<boolean>(false); // 默认折叠
  const { download, downloading } = useDownload();

  // 渲染参数值的通用函数
  const renderParameterValue = (parameter: Parameter) => {
    if (parameter.type === 'string') {
      return (
        <span className="font-medium text-gray-900">{parameter.value}</span>
      );
    }

    if (parameter.type === 'object' && parameter.value) {
      return (
        <div className="space-y-1">
          {Object.entries(parameter.value).map(([key, value]) => (
            <div key={key} className="flex items-center justify-between">
              <span className="text-xs text-gray-500">{key}:</span>
              <span className="ml-2 text-sm font-medium text-gray-700">
                {typeof value === 'object'
                  ? JSON.stringify(value)
                  : String(value)}
              </span>
            </div>
          ))}
        </div>
      );
    }

    if (parameter.type === 'array') {
      return (
        <div className="flex flex-wrap gap-1">
          {(parameter.value || []).map((item: any, index: number) => (
            <span
              key={index}
              className="inline-flex items-center rounded-md bg-blue-50 px-2 py-1 text-xs font-medium text-blue-700"
            >
              {typeof item === 'object' ? JSON.stringify(item) : String(item)}
            </span>
          ))}
        </div>
      );
    }

    if (parameter.type === 'boolean') {
      return (
        <span
          className={`inline-flex items-center rounded-full px-2 py-1 text-xs font-medium ${
            parameter.value
              ? 'bg-green-100 text-green-800'
              : 'bg-red-100 text-red-800'
          }`}
        >
          {parameter.value ? '是' : '否'}
        </span>
      );
    }

    if (parameter.type === 'number') {
      return (
        <span className="font-mono text-sm font-medium text-purple-700">
          {parameter.value}
        </span>
      );
    }

    return <span className="italic text-gray-500">暂无数据</span>;
  };

  const handleDelete = async (id: string) => {
    const res = await clientFetch.delete('/api/plans', {
      params: {
        id,
      },
    });

    if (res.code === 200) {
      Toast.success('删除成功');
    }
  };

  const handleShowDetail = () => {};

  return (
    <div
      className={clsx(
        'group rounded-2xl border border-white/50 bg-white p-6 shadow-sm transition-all duration-300 hover:shadow-md',
        className
      )}
    >
      <div className="mb-4 flex items-start justify-between">
        <div className="flex-1">
          <div className="mb-2 flex items-center space-x-3">
            <h3 className="text-xl font-semibold text-semi-color-text-1 transition-colors duration-200 group-hover:text-blue-600">
              {record.template}
            </h3>
            <span className="inline-flex items-center rounded-full border border-blue-200 bg-blue-100 px-3 py-1 text-xs font-medium text-blue-800">
              {record.version}
            </span>
          </div>

          {/* 基础信息网格 */}
          <div className="grid grid-cols-1 gap-4 text-sm text-gray-600 md:grid-cols-2 lg:grid-cols-4">
            <div className="flex items-center space-x-2">
              <Icon icon="lucide:user" className="h-4 w-4" />
              <span>{record.creator}</span>
            </div>
          </div>

          {/* 参数预览 - 只有参数存在时才显示 */}
          {record.parameter && record.parameter.length > 0 && (
            <div className="mt-4">
              <button
                onClick={() => setIsOpen(!isOpen)}
                className="flex w-full items-center justify-between rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 text-left transition-all duration-200 hover:bg-gray-100"
              >
                <div className="flex items-center space-x-3">
                  <Icon
                    icon="lucide:settings"
                    className="h-4 w-4 text-gray-500"
                  />
                  <span className="text-sm font-medium text-gray-700">
                    模板参数 ({record.parameter.length})
                  </span>
                </div>
                <Icon
                  icon={isOpen ? 'lucide:chevron-up' : 'lucide:chevron-down'}
                  className="h-4 w-4 text-gray-400 transition-transform duration-200"
                />
              </button>

              <Collapsible isOpen={isOpen}>
                <div className="mt-3 space-y-4 rounded-lg border border-gray-200 bg-white p-4">
                  {record.parameter.map((parameter, index) => (
                    <div
                      key={index}
                      className="flex items-start justify-between border-b border-gray-100 pb-3 last:border-b-0 last:pb-0"
                    >
                      <div className="flex-1">
                        <div className="mb-2 flex items-center space-x-2">
                          <span className="text-sm font-semibold text-gray-800">
                            {parameter.key}
                          </span>
                          <span className="inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600">
                            {parameter.type}
                          </span>
                        </div>

                        {parameter.description && (
                          <p className="mb-2 text-xs text-gray-500">
                            {parameter.description}
                          </p>
                        )}

                        <div className="flex items-center space-x-2">
                          {renderParameterValue(parameter)}
                        </div>
                      </div>
                    </div>
                  ))}

                  {/* 参数统计信息 */}
                  <div className="mt-4 flex items-center justify-between border-t border-gray-200 pt-3">
                    <div className="flex items-center space-x-4 text-xs text-gray-500">
                      <span>总参数: {record.parameter.length}</span>
                      <span>
                        已配置:{' '}
                        {
                          record.parameter.filter(
                            (p) =>
                              p.value !== undefined &&
                              p.value !== null &&
                              p.value !== ''
                          ).length
                        }
                      </span>
                    </div>
                  </div>
                </div>
              </Collapsible>
            </div>
          )}
        </div>

        {/* 操作按钮 */}
        <div className="flex items-center space-x-2 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
          <Popconfirm
            title="确认删除"
            content="删除后无法恢复，确定要删除这条工艺流程吗？"
            onConfirm={() => handleDelete(record._id)}
          >
            <button
              className="rounded-lg p-2 text-red-400 transition-all duration-200 hover:bg-red-50 hover:text-red-600"
              title="删除方案"
            >
              <Icon icon="lucide:delete"></Icon>
            </button>
          </Popconfirm>
          <Tooltip content="查看详情">
            <button
              className="rounded-lg p-2 text-gray-400 transition-all duration-200 hover:bg-green-50 hover:text-green-600"
              title="查看详情"
              onClick={handleShowDetail}
            >
              <Icon icon="lucide:eye"></Icon>
            </button>{' '}
          </Tooltip>

          <Tooltip content="下载方案">
            <Button
              className="rounded-lg p-2 text-gray-400 transition-all duration-200 hover:bg-purple-50 hover:text-purple-600"
              title="下载方案"
              onClick={() => {  
                console.log(record.file.filename);
                download(record.file.url, {
                  filename: record.file.filename,
                });
              }}
              loading={downloading}
            >
              <Icon icon="lucide:download"></Icon>
            </Button>
          </Tooltip>
        </div>
      </div>

      {/* 底部信息 */}
      <div className="flex items-center justify-between border-t border-gray-100 pt-4">
        <div className="flex items-center space-x-4 text-xs text-gray-500">
          <span>
            创建时间: {format(record.createdAt, 'yyyy-MM-dd HH:mm:ss')}
          </span>
          <span>
            更新时间: {format(record.updatedAt, 'yyyy-MM-dd HH:mm:ss')}
          </span>
          {/* <span>文件大小: {formatFileSize(record.file.metadata.size)}</span> */}
        </div>

        <div className="text-xs text-gray-400">ID: {'66'}</div>
      </div>
    </div>
  );
}
